package com.qire.manhua.view.linkageBehaviors;

import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.OverScroller;

import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.manhua.R;
import com.qire.manhua.view.CanInterceptFrameLayout;
import com.qire.manhua.view.comicReader.ComicReaderView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.coordinatorlayout.widget.CoordinatorLayout.Behavior;
import androidx.core.view.ViewCompat;
import androidx.core.widget.NestedScrollView;

public class QuickReadBehavior extends Behavior<View> {

    public QuickReadBehavior() {
        super();
    }

    public QuickReadBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(CoordinatorLayout parent, View child, MotionEvent ev) {
        stopFlingBehavior();
//        HomePageTopBarViewHelper.getHelper().stopFlingBehavior();
        return super.onInterceptTouchEvent(parent, child, ev);
    }

    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int axes, int type) {
        if (type == ViewCompat.TYPE_TOUCH) {
            return onStartNestedScroll(coordinatorLayout, child, directTargetChild,target, axes);
        }
        return false;
    }
    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) {
        boolean startNestedScroll = child instanceof NestedScrollView;
        if(startNestedScroll){
            onMeasure(coordinatorLayout, (NestedScrollView) child);
        }
        return startNestedScroll;
//        return child.getId() == R.id.appbar_layout /*&& nestedScrollAxes == View.SCROLL_AXIS_VERTICAL*/;
    }

    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed, int type) {
        if (type == ViewCompat.TYPE_TOUCH) {
            onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
        }
    }
    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed) {
        stopFlingBehavior();
        handlerScrollBehavior(coordinatorLayout,dy);
    }

    @Override
    public void onStopNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target) {
//        HomePageTopBarViewHelper.getHelper().handlerFlingBehavior(coordinatorLayout);
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onNestedPreFling(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, float velocityX, float velocityY) {

//        HomePageTopBarViewHelper.getHelper().handlerFlingBehavior(coordinatorLayout);
//        stopFlingBehavior();
        handlerFlingBehavior(coordinatorLayout, (int) velocityY);

        return false;
    }



    private final int dp100 = EquipmentInfoUtil.dip2px(100);
    private int comicTopHeadViewHeight;
    private int comicReaderViewHeight;
    private int bottomMenuViewHeight;

    private void onMeasure(CoordinatorLayout coordinatorLayout,NestedScrollView scrollView){
        View comicTopHead       = coordinatorLayout.findViewById(R.id.comicTopHead);
        View bottomMenu         = coordinatorLayout.findViewById(R.id.bottomMenu);
        View comicReaderView    = coordinatorLayout.findViewById(R.id.comicReaderView);

        comicTopHeadViewHeight  = comicTopHead.getHeight();
        comicReaderViewHeight   = comicReaderView.getHeight();
        bottomMenuViewHeight    = bottomMenu.getHeight();

    }

    private void handlerScrollBehavior(@NonNull CoordinatorLayout coordinatorLayout,int dy){

        View comicTopHead   = coordinatorLayout.findViewById(R.id.comicTopHead);
        View bottomMenu     = coordinatorLayout.findViewById(R.id.bottomMenu);
        ComicReaderView comicReaderView = coordinatorLayout.findViewById(R.id.comicReaderView);
        CanInterceptFrameLayout comicTitlePanel = coordinatorLayout.findViewById(R.id.comicTitlePanel);

        int[] consumed = {0,0};

//        comicReaderView.scrollBy(0,-dy);
        if(dy > 0) {
            transformComicTitle(comicTitlePanel,comicTopHead, dy, consumed);
            moveComicTopHead(comicTopHead, dy, consumed);
            moveComicReaderView(comicReaderView, bottomMenu, dy, consumed);
        } else {
            moveComicReaderView(comicReaderView, bottomMenu, dy, consumed);
            moveComicTopHead(comicTopHead, dy, consumed);
            transformComicTitle(comicTitlePanel,comicTopHead, dy, consumed);
        }

    }

    private boolean isFirst = false;
    private long firstTime = 0;
    private void transformComicTitle(View comicTitlePanel, View comicTopHead, int dy, int[] consumed){
        //屏蔽0距离移动，会引起闪烁
        if(dy == 0)
            return;
        long nowTime = System.currentTimeMillis();
        if(nowTime - firstTime <500)
            return;
        boolean needShow = comicTopHead.getBottom() <= 0 && (dy < 0 || !isFirst);
        if(needShow) {
            isFirst=true;
            firstTime = System.currentTimeMillis();
            if(comicTitlePanel.getVisibility() == View.VISIBLE)
                return;
            Animation animation = AnimationUtils.loadAnimation(comicTitlePanel.getContext(), R.anim.app_quick_read_topbar_in);
            //开启动画
            comicTitlePanel.startAnimation(animation);
            comicTitlePanel.setVisibility(View.VISIBLE);
        } else {
            if(comicTitlePanel.getVisibility() == View.GONE)
                return;
            Animation animation = AnimationUtils.loadAnimation(comicTitlePanel.getContext(), R.anim.app_quick_read_topbar_out);
            //开启动画
            comicTitlePanel.startAnimation(animation);
            comicTitlePanel.setVisibility(View.GONE);
        }
    }

    private void moveComicTopHead(View comicTopHead, int dy, int[] consumed){

        int canMoveY = dy - consumed[1];

        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) comicTopHead.getLayoutParams();

        int oldTopMargin = layoutParams.topMargin;
        int newTopMargin = Math.min(dp100, Math.max(-comicTopHead.getHeight(),oldTopMargin - canMoveY));
        layoutParams.topMargin = newTopMargin;
        comicTopHead.requestLayout();

        consumed[1] = (oldTopMargin - newTopMargin) + consumed[1];
//        consumed[1] = dy - consumed[1];

    }

    private void moveComicReaderView(ComicReaderView comicReaderView, View bottomMenu, int dy, int[] consumed){

        int canMoveY = dy - consumed[1];

        Point oldPoint = comicReaderView.getScroll();
        comicReaderView.scrollBy(0, -canMoveY);
        Point newPoint = comicReaderView.getScroll();
        consumed[1] = (oldPoint.y - newPoint.y) + consumed[1];

        if(comicReaderView.isToTheBottom()) {
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) bottomMenu.getLayoutParams();
            int oldBottomMargin = layoutParams.bottomMargin;
            layoutParams.bottomMargin = Math.min(0,oldBottomMargin + canMoveY);
        } else if(dy<0) {
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) bottomMenu.getLayoutParams();
            int oldBottomMargin = layoutParams.bottomMargin;
            layoutParams.bottomMargin = Math.max(-layoutParams.height,oldBottomMargin + canMoveY);
        }

    }


    private AnimatorTask task = null;
    public void handlerFlingBehavior(CoordinatorLayout coordinatorLayout,int velocityY){
        stopFlingBehavior();
        task = new AnimatorTask(coordinatorLayout);
        task.fling(velocityY).start();
    }

    public void stopFlingBehavior(){
        if(task != null)
            task.isRunning = false;
    }

    public class AnimatorTask extends Thread {

        private volatile boolean isRunning=true;
        private long duration = 1;
        private CoordinatorLayout coordinatorLayout;

        private final OverScroller scroller;

        private int scrollX =0, scrollY = 0;

        public AnimatorTask(CoordinatorLayout coordinatorLayout){
            this.coordinatorLayout = coordinatorLayout;
            this.scroller = new OverScroller(coordinatorLayout.getContext());
        }

        public AnimatorTask fling(int velocityY){
            scrollX=scrollY=0;
            this.scroller.fling(scrollX,scrollY,0,velocityY,0,0, Integer.MIN_VALUE, Integer.MAX_VALUE);
            return this;
        }

        @Override
        public void run() {
            long time = 0;
            while (time <= 3000 && isRunning) {
                try {
                    boolean more = scroller.computeScrollOffset();
                    if(!more){
                        isRunning = false;
                        scroller.abortAnimation();
                        continue;
                    }
                    int currY = scroller.getCurrY();
                    int dy = currY - scrollY;
                    scrollY = currY;
                    coordinatorLayout.post(()->handlerScrollBehavior(coordinatorLayout,dy));
                    time += duration;
                    Thread.sleep(duration);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }


}
